#include "graphicsframemodel.h"

const int GraphicsFrameModel::ROTATE = 270;

GraphicsFrameModel::GraphicsFrameModel(AnimationDataHandler* coreData, QObject *parent)
    : QObject(parent),  
    m_item(NULL),
    m_coreData(coreData),
    m_fullFileName(""),
    m_fullPixMp(NULL)
{
    m_scene = new QGraphicsScene();
}

GraphicsFrameModel::~GraphicsFrameModel()
{
    clearAllData();
    CC_SAFE_DELETE_NULL(m_scene);
}


void GraphicsFrameModel::dataChangeUpdate()
{
    PlistFrameInfo* frameInfo = m_coreData->getCurrentFrame();
    if(frameInfo == NULL)
    {
        clearAllData();
        return;
    }

    clearAllData();

    QString fullFileName = m_workingDir + "/" + frameInfo->plistPngName;
    if(m_fullFileName != fullFileName)
    {
        CC_SAFE_DELETE_NULL(m_fullPixMp);
        m_fullFileName = fullFileName;
        m_fullPixMp = new QPixmap(m_fullFileName);
    }

    QRectF rect = frameInfo->sizeRect;
    if(frameInfo->isRotated)
    {
        int w = rect.height();
        rect.setHeight(rect.width());
        rect.setWidth(w);
    }

    QPixmap pieceImage = m_fullPixMp->copy(rect.x(),rect.y(),rect.width(),rect.height());
    m_item = new QGraphicsPixmapItem(pieceImage);

    qreal scaleX = m_viewRect.width() /frameInfo->sourceRectPoint.x() ;
    qreal scaleY =  m_viewRect.height() / frameInfo->sourceRectPoint.y();

    m_item->translate(frameInfo->sourceColorRect.x() * scaleX, frameInfo->sourceColorRect.y() * scaleY);

    if(frameInfo->isRotated)
    {
        m_item->setRotation(ROTATE);
    }

    m_scene->addItem(m_item);

    emit notifyDisplayUpdate();
}

void GraphicsFrameModel::clearAllData()
{
    if(m_scene->items().count() > 0)
    {    
        m_scene->removeItem(m_item);
        CC_SAFE_DELETE_NULL(m_item);
    }
}

void GraphicsFrameModel::setWorkingDir(QString &workingDir)
{
    m_workingDir = workingDir;
}

